package lu.uni.adtool.adtree;

import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Toolkit;

import org.abego.treelayout.NodeExtentProvider;

import lu.uni.adtool.Options;

import lu.uni.adtool.ui.ADTreeCanvas;

/**
 * A {@link NodeExtentProvider} for nodes of type {@link TextInBox}.
 * <p>
 * As one would expect this NodeExtentProvider returns the width and height as
 * specified with each TextInBox.
 * 
 * @author Piot Kordy
 */
public class ADTLocalTNExtendProvider implements NodeExtentProvider<ADTreeNode>
{
  private final static int X_PADDING = 25;
  private final static int Y_PADDING = 15;
  private ADTreeCanvas owner;
  /**
   * Constructs a new instance.
   * @param owner canvas owning this instarce.
   */
  public ADTLocalTNExtendProvider(ADTreeCanvas owner)
  {
    this.owner = owner;
  }

  /**
   * {@inheritDoc}
   * @see NodeExtentProvider#getWidth(ADTreeNode)
   */
  public final double getWidth(final ADTreeNode node)
  {
    String label = owner.getLabel(node);
    return getSizeOfText(label).x;
  }

  /**
   * {@inheritDoc}
   * @see NodeExtentProvider#getHeight(ADTreeNode)
   */
  public final double getHeight(final ADTreeNode node)
  {
    String label = owner.getLabel(node);
    return getSizeOfText(label).y;
  }

  /**
   * Splits text to lines and calculates the size.
   * 
   * @param label
   */
  private final Point getSizeOfText(String label)
  {
    final FontMetrics m = Toolkit.getDefaultToolkit().getFontMetrics(
        Options.canv_Font);
    String result = "";
    String[] lines = label.split(System.getProperty("line.separator"));
    for (String line:lines){
      if(line.length()>result.length()){
        result = line;
      }
    }
    return new Point(m.stringWidth(result)+X_PADDING,m.getHeight()*lines.length+Y_PADDING);
  }
}

